package com.crazy.crazybusinessservice.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crazy.crazybusinessservice.mapper.TransactionMapper;
import com.crazy.crazybusinessservice.message.MqProducer;
import com.crazy.crazybusinessservice.service.StopService;
import com.crazy.crazycommon.constant.TransactionStatusConstant;
import com.crazy.crazycommon.constant.TransactionTypeConstant;
import com.crazy.crazymodel.model.entity.Transaction;
import com.crazy.crazyserviceclient.service.TransactionFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class StopImpl implements StopService {
    @Resource
    private MqProducer mqProducer;
    @Resource
    private TransactionMapper transactionMapper;

    @Resource
    private TransactionFeignClient transactionFeignClient;

    @Override
    public List<Transaction> TransactionStatusConfirmation() {
        return transactionMapper.selectTranscationByStatus();
    }

    @Override
    public void DetermineStatus(Integer id) {
        transactionMapper.updateStatusById(id);

    }

    @Override
    public void SubscribeHandle(Integer id) {
        String exchange = "confirm_exchange";
        String routingKey = "subscribe_key";
        log.info("发送消息：transactionId={}", id);
        mqProducer.sendMessage(exchange, routingKey, id);

    }

    @Override
    public void ReedemHandle(Integer id) {
        String exchange = "confirm_exchange";
        String routingKey = "redeem_key";
        log.info("发送消息：transactionId={}", id);
        mqProducer.sendMessage(exchange, routingKey, id);
    }

    @Override
    public void MainHandle() {
        List<Transaction> transactions = TransactionStatusConfirmation();
        for (Transaction transaction : transactions) {
            Integer transactionId = transaction.getTransactionId();

            int transactionType = transaction.getTransactionType();
            // 交易类型为1，执行申购处理
            if (transactionType == TransactionTypeConstant.SUBSCRIBE) {
                SubscribeHandle(transactionId);
            }
            // 交易类型为2，执行赎回处理
            else if (transactionType == TransactionTypeConstant.REDEEM) {
                ReedemHandle(transactionId);
            } else {
                log.error("交易类型错误");
            }
        }
    }
}
